<template>
	<view class="content">
		<!-- 首单礼金领取 -->
		<view class="goods-cash">
			<image mode="widthFix" class="cash-bg" src="https://onecode-zfx-one.oss-cn-shenzhen.aliyuncs.com/20200819/d01033a0-e1be-11ea-8cb1-cb2082e741d9.png"></image>
			<view class="cash-inner">
				<view class="cash-list">
					<form @submit="onSubmit" report-submit="true" v-for="(item, index) in firstList">
						<button form-type="submit" hover-class="none" @tap="receiveCash(item)" class="cash-item" :class="[{ red : index === 0}, { blue : index === 1}]">
							领取{{ index === 0 ? '首单' : '备用' }}礼金
						</button>
					</form>
				</view>
			</view>
		</view>

		<!-- 标题和撸单 -->
		<view class="goods-tool">
			<view class="title">礼金抵扣专区</view>
			<view class="course" @tap="toCourse">视频教程</view>
		</view>

		<!-- 搜索框 -->
		<view class="good-search">
			<view class="search-inner">
				<text class="iconfont icon-sousuo"></text>
				<input class="input" v-model="params.keyWord" @confirm="onSearch" @input="onInput" confirm-type="search"
				 placeholder-style="color: #9C9D9E;font-size: 28rpx;" placeholder="输入关键词搜索" />
				<text class="iconfont icon-guanbi" :class="[{ show : isShowClose}]" @tap="clearKeyword"></text>
			</view>
		</view>

		<!-- 已领礼金 -->
		<view class="receive-money">
			<text class="title">已领礼金：</text>
			<view class="receive-list">
				<view class="receive-item" v-for="item in receiveList" :class="[{ active : item.money === receiveMoney }]" @tap="receiveMoney = item.money">{{ item.money }}元</view>
			</view>
		</view>

		<!-- tab切换 -->
		<tab ref="tab" @tabChange="tabChangeCustom" :list="list" :stickyTop="206"></tab>

		<!--商品排序-->
		<view class="goods-sort">
			<sort v-for="(item, index) in filter.sort" :key="index" :active="item.active" :index="index" :order="item.order"
			 :title="item.title" @changeSort="changeSort">
			</sort>
		</view>

		<!-- 商品列表 -->
		<view class="goods-list">
			<goods-item v-for="(goodsItem, goodsIndex) in list[active].goodsList" :item="goodsItem" :key="goodsItem.gid"
			 @onCopySuccess="onCopySuccess" :receiveMoney="receiveMoney"></goods-item>

			<!-- 商品骨架 -->
			<template v-for="item in ['a', 'b', 'c', 'd']">
				<view class="skeleton-wrap" v-if="
						list[active].goodsList.length === 0 &&
							!list[active].finished &&
							!list[active].empty
					">
					<skeleton class="goods-skeleton" :loading="true" avatarShape="square" avatarSize="198rpx"></skeleton>
				</view>
			</template>

			<!-- 加载中插件 -->
			<view class="load-status">
				<load-more status="loading" color="#c6c6c6" iconType="circle" v-if="!list[active].finished && !list[active].empty"
				 :contentText="contentText"></load-more>
				<load-more status="noMore" color="#c6c6c6" v-if="list[active].finished" :contentText="contentText"></load-more>
				<empty v-if="list[active].empty"></empty>
			</view>
		</view>

		<!-- 去福利源代码 -->
		<view class="to-minisoft">
			<image class="image" @tap="toMiniSoft" src="https://onecode-zfx-one.oss-cn-shenzhen.aliyuncs.com/20200820/7c30f980-e2af-11ea-bcba-572c7b0f9cea.gif"></image>
		</view>

		<!--回到顶部-->
		<view class="scrollTop" :class="[{ show: isShowScrollTop }]" @tap="backTop">
			<text class="iconfont icon-huidaodingbu"></text>
		</view>

		<!-- 淘口令复制成功弹窗 -->
		<popup ref="copySuccess">
			<view class="copy-success">
				<text class="iconfont icon-guanbi" @tap="$refs.copySuccess.close()"></text>
				<image class="image" src="@/static/images/copy-success.png"></image>
				<view class="text">淘口令复制成功</view>
				<view class="text">打开【淘宝】领取首单礼金</view>
				<view class="red">只领首单礼金，不要下单!</view>
				<view class="time">{{ time }}秒后关闭</view>
			</view>
		</popup>
	</view>
</template>

<script>
	import Tab from '@/components/Tab'
	import Sort from '@/components/Sort'
	import GoodsItem from "@/components/GoodsItem";
	import LoadMore from "@/components/LoadMore";
	import Popup from "@/components/Popup";
	import Empty from "@/components/Empty";
	import Skeleton from '@/components/Skeleton';
	import loader from '@/utils/mixin/loader';

	export default {
		name: 'index',
		mixins: [loader],
		components: {
			Tab,
			Sort,
			GoodsItem,
			LoadMore,
			Popup,
			Empty,
			Skeleton
		},
		data() {
			return {
				firstList: [],
				time: 5,
				isShowClose: false,
				isTabLoading: true,
				receiveMoney: 7,
				receiveList: [{
						money: 7
					},
					{
						money: 6
					},
					{
						money: 5
					},
					{
						money: 4
					},
					{
						money: 3
					},
					{
						money: 2
					}
				],
				filter: {
					sort: [{
							title: '人气',
							active: true,
							order: 'desc'
						},
						{
							title: '销量',
							active: false,
							order: ''
						},
						{
							title: '价格',
							active: false,
							order: ''
						},
						{
							title: '最近',
							active: false,
							order: ''
						}
					]
				},
				seqencing: {
					order: 'sale2',
					sort: 'desc',
				},
				contentText: {
					contentdown: '上拉显示更多哦~',
					contentrefresh: "皮小丘正在拼命加载中...",
					contentnomore: "皮小丘也是有底线的~"
				},
				options: {},
				interval: null
			}
		},
		onShareAppMessage() {
			return {
				title: '嗨返皮卡丘',
				desc: '首单礼金领取，为用户的购物提供优惠',
				bgImgUrl: 'https://onecode-zfx-one.oss-cn-shenzhen.aliyuncs.com/20200828/00015a40-e8fd-11ea-8265-f7afd3fb938e.png'
			};
		},
		onLoad(options) {
			if (options) {
				this.options = options;
			}
			this.initLoader();
		},
		methods: {
			// 加载初始化
			initLoader() {
				uni.showLoading({
					title: '加载中...'
				})
				// 获取首单商品
				this.$service.shopping.goods.firstList().then((res) => {
					this.firstList = res;
					uni.hideLoading();
				});

				// 获取商品分类
				this.$service.shopping.classify.list({
					specialType: 103,
				}).then(res => {
					res.forEach(item => {
						item.label = item.mainName;
						item.loading = false;
						item.finished = false;
						item.error = false;
						item.page = 1;
						item.goodsList = [];
					});
					this.list = this.list.concat(res);

					this.loadMore(this.list[0]);
				});
			},
			// 加载前参数处理
			beforeLoader(item) {
				if (this.options && this.options.keyWord) {
					this.params.keyWord = this.options.keyWord;
					this.isShowClose = true;
				}
				if (item.floorId) {
					this.params.catId = item.floorId;
				} else {
					this.params.catId = null;
				}
				this.params.order = this.seqencing.order;
				this.params.sort = this.seqencing.sort;
				this.service = this.$service.shopping.goods.page(this.params);
				return true;
			},
			// 加载后操作
			afterLoader() {

			},
			// 触发商品搜索
			onSearch(e) {
				// 区分苹果安卓平台
				if (uni.getSystemInfoSync().platform === 'android') {
					uni.reLaunch({
						url: '/pages/index/index?keyWord=' + e.detail.value
					});
				} else {
					this.params.keyWord = e.detail.value;
					this.list.forEach(item => {
						item.goodsList = [];
						item.loading = false;
						item.finished = false;
						item.empty = false;
						item.page = 1;
					});
					uni.pageScrollTo({
						scrollTop: 0,
						duration: 0
					});
					this.onRefresh(this.list[this.active]);
				}
			},
			// 触发关键词更新
			onInput(e) {
				if (e.detail.value) {
					this.isShowClose = true;
				} else {
					this.isShowClose = false;
				}
			},
			// 清除关键词
			clearKeyword() {
				this.options = null;
				this.params.keyWord = '';
				this.isShowClose = false;
				this.list.forEach(item => {
					item.goodsList = [];
					item.loading = false;
					item.finished = false;
					item.empty = false;
					item.page = 1;
				});

				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0
				});
				this.onRefresh(this.list[this.active]);
			},
			// 去教程页
			toCourse() {
				uni.navigateTo({
					url: '/pages/index/course'
				})
			},
			// 静默提交消息推送
			onSubmit(e) {
				let vm = this;
				my.getAuthCode({
					scopes: 'auth_base', // 主动授权（弹框）：auth_user，静默授权（不弹框）：auth_base
					success: (codeRes) => {
						if (codeRes.authCode) {
							vm.$service.common.alipass.getAlipayUserid({
								platform: 'hfpkq',
								code: codeRes.authCode
							}).then(userRes => {
								vm.$service.common.alipayXcx
									.save({
										userId: userRes.userId,
										formId: e.detail.formId,
										authCode: codeRes.authCode,
										app: 'hfpkq'
									})
							})
						}
					}
				})
			},
			// 领取礼金
			receiveCash(item) {
				let vm = this;

				uni.showLoading({
					title: '正在生成淘口令...'
				});

				let params = {
					title: item.title,
					itemId: item.gid,
					url: item.url
				};
				this.$service.shopping.taobao.privilege(params).then(res => {
					uni.hideLoading();
					uni.setClipboardData({
						data: res.tkl,
						success: function() {
							vm.onCopySuccess();
						},
						fail: function() {
							uni.showToast({
								title: '复制失败',
								icon: 'none'
							})
						}
					});
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon: 'none'
					})
				})
			},
			// 淘口令复制成功
			onCopySuccess(url) {
				if (url) {
					my.navigateToMiniProgram({
						appId: '2018091261350219',
						path: `/pages/h5pages/h5pages?targetURI=${url}`,
						success: res => {
							console.log(JSON.stringify(res));
						},
						fail: res => {
							console.log(JSON.stringify(res));
						}
					});
				} else {
					this.time = 5;
					this.$refs.copySuccess.open();

					clearInterval(this.interval);
					this.interval = setInterval(() => {
						this.time--;
					}, 1000);

					setTimeout(() => {
						this.$refs.copySuccess.close();

						clearInterval(this.interval);
					}, 5000);
				}
			},
			// 筛选切换
			changeSort(index, order) {
				this.filter.sort.forEach(item => {
					item.active = false;
					item.order = '';
				});
				this.filter.sort[index].order = order;
				this.filter.sort[index].active = true;

				this.seqencing.sort = order;

				switch (index) {
					case 0:
						this.seqencing.order = 'sale2';
						break;
					case 1:
						this.seqencing.order = 'sale';
						break;
					case 2:
						this.seqencing.order = 'estimatePrice';
						break;
					case 3:
						this.seqencing.order = 'fristOrder';
						break;
					default:
						this.seqencing.order = '';
				}
				if (!order) {
					this.seqencing.order = '';
				}

				this.params.page = 1;
				this.onRefresh(this.list[this.active]);
			},
			// 自定义tab切换
			tabChangeCustom(index) {
				if (this.list[index].goodsList.length > 6) {
					this.tabChange(index, 278);
				} else {
					this.tabChange(index);
				}
			},
			// 跳转至福利源代码
			toMiniSoft() {
				my.navigateToMiniProgram({
					appId: '2021001185637545',
					path: 'pages/zfb/redPage',
					success: res => {
						console.log(JSON.stringify(res));
					},
					fail: res => {
						console.log(JSON.stringify(res));
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		min-height: 100%;

		.goods-cash {
			height: 546rpx;
			background: #fff;
			position: relative;

			.cash-bg {
				width: 100%;
				position: absolute;
			}

			.cash-inner {
				position: relative;
				width: 620rpx;
				margin: 0 auto;
				padding-top: 344rpx;
				@include flexBox(null, null, column);

				.cash-list {
					height: 92rpx;
					width: 100%;
					@include flexBox(center, center);

					.cash-item {
						width: 248rpx;
						height: 68rpx;
						line-height: 64rpx;
						border-radius: 20rpx;
						text-align: center;
						font-size: 28rpx;
						box-sizing: border-box;
						border: 2rpx solid #fff;
						color: #fff;
						margin: 0 24rpx 10rpx;

						&.red {
							background: linear-gradient(90deg, rgba(255, 64, 136, 1) 0%, rgba(255, 114, 167, 1) 49%, rgba(255, 64, 136, 1) 100%);
						}

						&.blue {
							background: linear-gradient(270deg, rgba(168, 95, 254, 1) 0%, rgba(249, 26, 174, 1) 100%);
						}
					}
				}
			}
		}

		.goods-tool {
			position: relative;
			background: #fff;
			position: sticky;
			z-index: 100;
			top: 0;

			.title {
				text-align: center;
				font-weight: 600;
				font-size: 32rpx;
				line-height: 60rpx;
			}

			.course {
				z-index: 100;
				position: absolute;
				right: 0;
				top: 0;
				line-height: 52rpx;
				font-size: 26rpx;
				color: #fff;
				letter-spacing: 2rpx;
				padding: 0 12rpx 0 18rpx;
				border-radius: 50rpx 0 0 50rpx;
				border-left: 4rpx solid #FFF3CA;
				border-top: 4rpx solid #FFF3CA;
				border-bottom: 4rpx solid #FFF3CA;
				background: #FF4088;
				box-sizing: border-box;
			}
		}

		.good-search {
			background: #fff;
			padding: 20rpx 16rpx;
			position: sticky;
			top: 56rpx;
			z-index: 100;

			.search-inner {
				width: 708rpx;
				height: 60rpx;
				border-radius: 50rpx;
				background: #fff;
				padding: 0 26rpx;
				border: 2rpx solid #FF4088;
				box-sizing: border-box;
				color: #9C9D9E;
				margin: 0 auto;
				@include flexBox(space-between, center);

				.icon-sousou {
					font-size: 40rpx;
				}

				.icon-guanbi {
					font-size: 30rpx;
					margin-left: 10rpx;
					transition: 0.5s;
					opacity: 0;

					&.show {
						opacity: 1;
					}
				}

				.input {
					font-size: 28rpx;
					color: #9C9D9E;
					flex: 1;
					text-align: center;
					background: none;
				}
			}
		}

		.receive-money {
			background: #fff;
			font-size: 26rpx;
			height: 50rpx;
			position: sticky;
			top: 156rpx;
			z-index: 100;
			@include flexBox(center, center);

			.receive-list {
				@include flexBox(center, center);

				.receive-item {
					padding: 6rpx 16rpx;
					border-radius: 8rpx;
					margin: 0 5rpx;
					background: #F4F5F6;
					color: #505050;
					transition: 0.5s;

					&.active {
						background: $uni-color-primary;
						color: #fff;
					}
				}
			}
		}

		.goods-sort {
			background: #fff;
			padding: 22rpx 0;
			position: sticky;
			z-index: 100;
			top: 282rpx;
			@include flexBox(center, center);
		}

		.goods-list {
			margin-top: 20rpx;
			padding: 0 10rpx;
			@include flexBox(flex-start, null, null, wrap);

			.skeleton-wrap {
				width: 710rpx;
				background: #fff;
				border-radius: 16rpx;
				margin: 0 10rpx 20rpx 10rpx;
			}

			.load-status {
				width: 100%;
				margin-top: -20rpx;
				@include flexBox(center);
			}
		}

		.to-minisoft {
			width: 150rpx;
			height: 150rpx;
			position: fixed;
			top: 72vh;
			right: 8rpx;
			z-index: 1000;

			.image {
				width: 100%;
				height: 100%;
			}
		}
	}

	@keyframes scale_loop {
		0% {
			transform: scale(1);
		}

		50% {
			transform: scale(1.05);
		}

		100% {
			transform: scale(1);
		}
	}

	.copy-success {
		width: 452rpx;
		height: 388rpx;
		background: #fff;
		border-radius: 16rpx;
		position: relative;
		@include flexBox(center, center, column);

		.icon-guanbi {
			position: absolute;
			right: 10rpx;
			top: 10rpx;
			color: #DEDEDE;
			font-size: 40rpx;
		}

		.image {
			width: 108rpx;
			height: 97rpx;
			margin-bottom: 20rpx;
		}

		.text {
			font-size: 28rpx;
			color: #2E2D2D;
			margin-top: 10rpx;
		}

		.red {
			color: $uni-color-primary;
			font-size: 28rpx;
			margin-top: 10rpx;
		}

		.time {
			color: #7E7E7E;
			font-size: 24rpx;
			margin-top: 20rpx;
		}
	}
</style>
